package com.boss.fileapp.util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * 生成MAC
 * byte[] key = pbocMac.hex2byte(key1.getBytes());
 *
 * macData 报文数据
 * byte[] macData = pbocMac.byte2Hex(macdata1.getBytes()).getBytes();
 *
 * byte[] mac = pbocMac.CalcPBOCMacX919(key, macData);
 *
 * String macStr = pbocMac.byte2Hex(mac);
 */

/**
 * AES加解密
 */
public class AESUtils {

    //文件缓冲区大小为4K
    private static int bufSize = 1024 * 4;

    /**
     * 生成秘钥
     * @return
     */
    public static byte[] generateAESKey() {
        //创建Key gen
        KeyGenerator keyGenerator;
        byte[] codeFormat = null;
        try {
            keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128, new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            codeFormat = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return codeFormat;
    }
    /**
     * 初始化 AES Cipher
     * @param sKey
     * @param cipherMode
     * @return
     */
    public static Cipher initAESCipherB(byte[] sKey, int cipherMode) {
        Cipher cipher = null;
        try {
            SecretKeySpec key = new SecretKeySpec(sKey, "AES");
            cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            //初始化
            cipher.init(cipherMode, key);
        } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return cipher;
    }
    /**
     * 对文件进行AES加密，密钥是以16进制字节流的方式输入
     * @param sourceFile
     * @param outFileName
     * @param sKey
     * @return
     */
    public static File encryptFile(File sourceFile, String outFileName, String sKey) {
        //新建临时加密文件
        File encrypfile = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(sourceFile);
            encrypfile = new  File(outFileName);
            outputStream = new FileOutputStream(encrypfile);
            Cipher cipher = initAESCipherB(MACUtils.hex2byte(sKey.getBytes()),Cipher.ENCRYPT_MODE);
            //以加密流写入文件
            CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
            byte[] cache = new byte[bufSize];
            int nRead = 0;
            while ((nRead = cipherInputStream.read(cache)) != -1) {
                outputStream.write(cache, 0, nRead);
                outputStream.flush();
            }
            cipherInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return encrypfile;
    }
    /**
     * AES方式解密文件
     * @param sourceFile
     * @param outFileName
     * @param sKey
     * @return
     */
    public static File decryptFile(File sourceFile,String outFileName,String sKey){
        File decryptFile = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            decryptFile = new File(outFileName);
            Cipher cipher = initAESCipherB(MACUtils.hex2byte(sKey.getBytes()),Cipher.DECRYPT_MODE);
            inputStream = new FileInputStream(sourceFile);
            outputStream = new FileOutputStream(decryptFile);
            CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
            byte [] buffer = new byte [bufSize];
            int r;
            while ((r = inputStream.read(buffer)) >= 0) {
                cipherOutputStream.write(buffer, 0, r);
            }
            cipherOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }finally {
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            try {
                if(outputStream != null){
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return decryptFile;
    }



}
